import React,{ useReducer,useEffect  } from 'react';
import NavHome from '../NavHome/NavHome';
import { ListView,Icon,Toast,NavBar,PullToRefresh } from 'antd-mobile';
import { newsList } from '../../api/Cms';
import './List.scss'


let dataList=[],dataArr=[],dataSource = new ListView.DataSource({
  rowHasChanged: (row1, row2) => row1 !== row2 // rowHasChanged(prevRowData, nextRowData); 用其进行数据变更的比较
}),initState = {
  dataSource,
  datas: [],
  page: 1,
  pageSize:10,
  hasMore: true,
  refreshing: true,
  isLoading: true,
  dataArr: [],
}
function stateReducer(state, action) {
  switch(action.type) {
      case 'nodata':
          return {
              ...state,
              refreshing: false,
              isLoading: false,
              hasMore: false,
          }
      case 'onRefresh':
          return {
              ...state,
              page: state.page,
              dataSource: state.dataSource.cloneWithRows(dataList), // 数据源中的数据本身是不可修改的,要更新datasource中的数据，请（每次都重新）调用cloneWithRows方法
              hasMore: true, // 下拉刷新后，重新允许开下拉加载
              refreshing: false, // 是否在刷新数据
              isLoading: false, // 是否在加载中
              dataArr: dataList // 保存数据进state，在下拉加载时需要使用已有数据
          }
      case 'onRefreshGet':
        return {
          ...state,
          refreshing: true,
          isLoading: true,
          page: 1 // 刷新嘛，一般加载第一页，或者按你自己的逻辑（比如每次刷新，换一个随机页码）
        }    
      case 'onEndReached':
          return {
              ...state,
              page: state.page,
              dataSource: state.dataSource.cloneWithRows(dataArr), // 数据源中的数据本身是不可修改的,要更新datasource中的数据，请（每次都重新）调用cloneWithRows方法
              refreshing: false,
              isLoading: false,
              dataArr: dataArr // 保存新数据进state
          }
      case 'next':
        return {
            ...state,
            isLoading: true,
            page:state.page + 1
        }    
      default: 
          return state;
  }
}
export default  function List(props) {
  const [state, dispatch] = useReducer(stateReducer, initState);
  const getData =(ref = false)=>{
        //获取数据
        var para = {}
        para.pageSize = state.pageSize
        para.page = state.page
        newsList(para.page,para.pageSize).then((res)=>{
               dataList = res.data
            if (!dataList) { // 判断是否已经没有数据了
                dispatch({ type: 'nodata' })
                Toast.info('没有数据了~', 1)
                return false
            }
            if (ref) {
                //这里表示刷新使用
                // 下拉刷新的情况，重新添加数据即可(这里等于只直接用了第一页的数据)
                dispatch({ type: 'onRefresh' })
               
            } else {
                // 这里表示上拉加载更多
                // 合并state中已有的数据和新增的数据
                 dataArr = state.dataArr.concat(dataList) 
                dispatch({type:'onEndReached'})
            }
        })
    }  

    useEffect(() => {
      // 使用浏览器的 API 更新页面标题
      getData(true)
    },[]);   
    
    // 下拉刷新
  const  onRefresh =()=>{
        dispatch({type:'onRefreshGet'}) 
        getData(true)
   }

  // 滑动到底部时加载更多
  const onEndReached = (event) => {
      // 加载中或没有数据了都不再加载
      if (state.isLoading || !state.hasMore) {
      return
      }
      dispatch({type:'next'})
      getData(false)

  }
  const separator = (sectionID, rowID) => (
    <div
      key={`${sectionID}-${rowID}`}
      style={{
        backgroundColor: 'rgb(250, 250, 250)',
        height: 8,
      
      }}
    />
  );
let row = (rowData, sectionID, rowID) => {
    // 这里rowData,就是上面方法cloneWithRows的数组遍历的单条数据了，直接用就行
    return (
     <div key={rowID} style={{ padding: '0 15px' }}>
        <div
          style={{
            lineHeight: '50px',
            color: '#888',
            fontSize: 18,
            borderBottom: '1px solid #F6F6F6',
          }}
        >{rowData.title}</div>
        <div style={{ display: '-webkit-box', display: 'flex', padding: '15px 0' }}>
          <img style={{ height: '64px', marginRight: '15px' }} src={rowData.pic} alt="" />
          <div style={{ lineHeight: 1 }}>
            <div style={{ marginBottom: '8px', fontWeight: 'bold',lineHeight:'20px',fontSize:'14px',fontWeight:'400' }}>{rowData.descript}</div>
           
          </div>
        </div>
      </div>
    )
  }
    return (
      <div>
               <div className="content-bg">
                <div className="content-box">
                <ListView
                    renderSeparator={separator}
                    // ref={el => this.lv = el}
                    dataSource={state.dataSource}
                    renderFooter={() => (<div className="footer">{state.isLoading ? '加载中...' : '暂无更多数据'}</div>)}
                    renderRow={row}
                    useBodyScroll
                    pullToRefresh={<PullToRefresh
                    refreshing={state.refreshing}
                    onRefresh={onRefresh}
                    />}
                    onEndReachedThreshold={10}
                    onEndReached={onEndReached}
                    pageSize={10}
                  
                />
                </div>
             </div>
             <NavHome/>
          </div>
    );
}

